package emd24.telstudyresources;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ResultsActivity extends Activity {

	private final String FILENAME = "progressFile";
	private Quiz quiz;
	private String currentDateTimeString;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_results);
		setTitle("Custom Quiz - Results");
		TextView score = (TextView) this.findViewById(R.id.score);
		Bundle b = this.getIntent().getExtras();
		this.quiz = b.getParcelable("quiz");
		score.setText("Score: " + this.quiz.getNumberCorrect() + " / " + 
				this.quiz.getNumQuestions());
		Button btnSave = (Button) this.findViewById(R.id.exit);

		ListView v = (ListView) this.findViewById(R.id.resultList);
		v.setAdapter(new ResultAdapter(this, this.quiz.toArray()));
		v.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {
				viewSolution(pos);
			}
			
		});


		// Set button listener
		btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				if (hasExistingProgressFile()) {
					addToCurrentProgressFile();
				}
				else {
					createNewProgressFile();
				}
				finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_results, menu);
		return true;
	}

	/**
	 * <p>This method creates a progress file JSON object in addition
	 * to a score object gets inserted, containing this instance's
	 * total number of question and total number of correct questions.</p>
	 * 
	 * <p>Context.MODE_PRIVATE is a mode to be used to make sure no other
	 * apps can access the data stored to internal persistant media.</p>
	 * 
	 * <Author>Matthew Hottinger</Author>
	 */
	private void createNewProgressFile() {
		currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
		String dataToWrite;
		dataToWrite = currentDateTimeString + "\t" + quiz.getNumberCorrect() + "\t" + quiz.getNumQuestions() + "\n";

		try {
			FileOutputStream outputStream = openFileOutput(FILENAME, Context.MODE_PRIVATE);
			outputStream.write(dataToWrite.getBytes());
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void addToCurrentProgressFile() {
		currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
		String dataToWrite;
		dataToWrite = currentDateTimeString + "\t" + quiz.getNumberCorrect() + "\t" + quiz.getNumQuestions() + "\n";
		
		try {
			FileOutputStream outputStream = openFileOutput(FILENAME, Context.MODE_APPEND);
			outputStream.write(dataToWrite.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * <p>Checks to see if the progress file already exists.</p>
	 * @return True if the progress file exists, false otherwise.
	 * 
	 * @Owner Matthew Hottinger
	 */
	private boolean hasExistingProgressFile() {
		File file = getBaseContext().getFileStreamPath(FILENAME);
		if(file.exists()){
			return true;
		}
		else{
			return false;
		}
	}
	/**
	 * Shows the solution for the a question at a given position
	 * in the quiz in a new activity.
	 * 
	 */
	private void viewSolution(int pos){
		Intent i = new Intent(this,SolutionActivity.class);
		i.putExtra("question", this.quiz.getQuestionAt(pos));
		startActivity(i);
	}
	/**
	 * This subclass is an adapter for the ListView in the ResultActivity. The
	 * class is private and cannot be accessed form other classes  
	 * 
	 * @author Owner
	 *
	 */
	private class ResultAdapter extends BaseAdapter {

		private Question[] questions;

		private ResultAdapter(Context c, Question[] questions){
			this.questions = questions;
			LayoutInflater.from(c);
		}

		@Override
		public int getCount() {
			return this.questions.length;
		}

		@Override
		public Object getItem(int position) {
			return this.questions[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView qNumber;
			TextView qCorrect;
			if(convertView == null){
				LayoutInflater inflater = LayoutInflater.from(parent.getContext());
				convertView = inflater.inflate(R.layout.result_row_view, parent, false);

			} 
			qNumber = (TextView) convertView.findViewById(R.id.qNumber);	
			qNumber.setText("Q" + this.questions[position].getQuestionNumber());
			qCorrect = (TextView) convertView.findViewById(R.id.answerCorrect);
			if(this.questions[position].isCorrect()){
				qCorrect.setTextColor(Color.GREEN);
				qCorrect.setText("Correct");
			}
			else{
				qCorrect.setTextColor(Color.RED);
				qCorrect.setText("Incorrect");
			}
			return convertView;
		}

	}
}
